﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="IndexCreator.cs" company="Data Ductus Malmö">
//   (c) 2010 - 2012 Data Ductus Malmö AB
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace DataDuctus.Snmp.Persistor.Core.Persistor.Internal
{
  using System.Linq;

  using DataDuctus.Snmp.Persistor.Core.MetaData;

  using Lextm.SharpSnmpLib;

  /// <summary>
  /// The index creator.
  /// </summary>
  internal static class IndexCreator
  {
    #region Methods

    /// <summary>
    /// The create index.
    /// </summary>
    /// <param name="classMeta">
    /// The class meta.
    /// </param>
    /// <param name="property">
    /// The property.
    /// </param>
    /// <param name="instance">
    /// The instance.
    /// </param>
    /// <returns>
    /// The Lextm.SharpSnmpLib.ObjectIdentifier.
    /// </returns>
    internal static ObjectIdentifier CreateIndex(ClassMeta classMeta, PropertyMeta property, object instance)
    {
      if (!classMeta.IsTable)
      {
        return new ObjectIdentifier(string.Format("{0}.{1}.0", classMeta.Oid, property.SubOid));
      }

      if (0 == classMeta.Indexes.Length)
      {
        return
          new ObjectIdentifier(
            string.Format("{0}.{1}.{2}", classMeta.Oid, property.SubOid, RenderPropertyOid(property, instance)));
      }

      string oid = classMeta.Indexes.Aggregate(
        string.Format("{0}.", classMeta.Oid), 
        (current, index) => current + string.Format("{0}.", RenderPropertyOid(index, instance)));

      return new ObjectIdentifier(oid.Substring(0, oid.Length - 1));
    }

    /// <summary>
    /// The render property oid.
    /// </summary>
    /// <param name="property">
    /// The property.
    /// </param>
    /// <param name="instance">
    /// The instance.
    /// </param>
    /// <returns>
    /// The System.String.
    /// </returns>
    internal static string RenderPropertyOid(PropertyMeta property, object instance)
    {
      object value = property.Property.GetValue(instance, null);

      return value.ToString();
    }

    #endregion
  }
}